//
//  LMPeituView.swift
//  WeiBo
//
//  Created by Li MAc on 2018/12/2.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import UIKit

class LMPeituView: UIView {
    
    @IBOutlet weak var ImgHeight:NSLayoutConstraint!
    
    @IBOutlet weak var peiandtoolbarHeight:NSLayoutConstraint!

    override func awakeFromNib() {
       setupUI()
    }
    
    var imgurls: [LMStatusPicture]? {
        didSet{
            //隐藏所有的 imgView
            for imgV in subviews{
                imgV.isHidden = true
            }
            //遍历 url 数组顺序设置图像
            var index = 0
           
            for url in imgurls ?? []  {
                //获得相对应的索引的ImageView
                let img = subviews[index] as! UIImageView
                let imgString = url.thumbnail_pic
                let imgURL = URL(string: imgString!)
                img.setImageWith(imgURL!, placeholderImage: nil)

                img.setImage(urlString: imgString, placeholderImage: nil)
                //显示图像
                img.isHidden = false
                index += 1
            }
        }
    }
    
    var peitue:WBStatusViewModel? {
        didSet{
            
            peitue?.pictureViewSize = setPictureViewSize(count: peitue?.picURL?.count ?? 0)
        }
    }
    
    /// 设置指定数量的图片对应的配图视图的大小
    ///
    /// - Parameter count: 配图数量
    /// - Returns: 返回视图大小
    private func setPictureViewSize(count:Int)-> CGSize {
        
        if count == 0 || count == nil {
            //返回空
            return CGSize()
        }
        
        
        //视图的高度  得知道行数
        let row = CGFloat(((count - 1) / 3) + 1)
        
        let pictureViewHeight = pictureItemWidth * row + (row - 1) * pictureViewInnerMargin
        
        return CGSize(width: pictureViewWidth, height: pictureViewHeight)
    }
}


extension LMPeituView {
    private func setupUI(){
        //超出边界不显示
        clipsToBounds = true
        
        let count = 9
        let re = CGRect(x: 0, y: 0, width: pictureItemWidth, height: pictureItemWidth)
        
        for i in 0..<count{
            let imgView = UIImageView()
            imgView.backgroundColor = UIColor.white
            //表示按比例缩放并且填满view
            imgView.contentMode = .scaleToFill
            //剪裁超出父视图范围的子视图部分
            imgView.clipsToBounds = true
            //行
            let row = CGFloat(i/3)
            //列
            let col = CGFloat(i%3)
            
            let x = col * (pictureItemWidth + pictureViewInnerMargin)
            
            let y = row * (pictureItemWidth + pictureViewInnerMargin)
            
            imgView.frame = re.offsetBy(dx: x, dy: y)
            
            addSubview(imgView)
        }
    }
}
